from django.http import JsonResponse, QueryDict
from django.views import View
from kubernetes import client, config,utils
from kubernetes.utils import FailToCreateError
from libs import k8s
import os,yaml,json
from libs.k8s import bytes_to_yaml
from libs import node_data


class export_yaml(View):

    k8s.load_auth_config()
    core_api = client.CoreV1Api()  # namespace,pod,service,pv,pvc
    apps_api = client.AppsV1Api()  # deployment
    networking_api = client.NetworkingV1Api()  # ingress
    storage_api = client.StorageV1Api()  # storage_class
    rbac_api = client.RbacAuthorizationV1Api()  # rbac

    def get(self,request):
        resource = request.GET.get('resource')
        namespace = request.GET.get('namespace')
        name = request.GET.get('name')

        try:
            if resource == "node":
                content = self.core_api.read_node(name=name, _preload_content=False).read()
                data = bytes_to_yaml(content)
            elif resource == "namespace":
                content = self.core_api.read_namespace(name=name, _preload_content=False).read()
                data = bytes_to_yaml(content)
            elif resource == "pv":
                content = self.core_api.read_persistent_volume(name=name, _preload_content=False).read()
                data = bytes_to_yaml(content)
            elif resource == "storageclass":
                content = self.storage_api.read_storage_class(name=name, _preload_content=False).read()
                data = bytes_to_yaml(content)
            elif resource == "deployment":
                content = self.apps_api.read_namespaced_deployment(namespace=namespace, name=name, _preload_content=False).read()
                data = bytes_to_yaml(content)
            elif resource == "replicaset":
                content = self.apps_api.read_namespaced_replica_set(namespace=namespace, name=name, _preload_content=False).read()
                data = bytes_to_yaml(content)
            elif resource == "daemonset":
                content = self.apps_api.read_namespaced_daemon_set(namespace=namespace, name=name, _preload_content=False).read()
                data = bytes_to_yaml(content)
            elif resource == "statefulset":
                content = self.apps_api.read_namespaced_stateful_set(namespace=namespace, name=name, _preload_content=False).read()
                data = bytes_to_yaml(content)
            elif resource == "pod":
                content = self.core_api.read_namespaced_pod(namespace=namespace, name=name,_preload_content=False).read()
                data = bytes_to_yaml(content)
            elif resource == "service":
                content = self.core_api.read_namespaced_service(namespace=namespace, name=name, _preload_content=False).read()
                data = bytes_to_yaml(content)
            elif resource == "ingress":
                content = self.networking_api.read_namespaced_ingress(namespace=namespace, name=name, _preload_content=False).read()
                data = bytes_to_yaml(content)
            elif resource == "pvc":
                content = self.core_api.read_namespaced_persistent_volume_claim(namespace=namespace, name=name, _preload_content=False).read()
                data = bytes_to_yaml(content)
            elif resource == "configmap":
                content = self.core_api.read_namespaced_config_map(namespace=namespace, name=name, _preload_content=False).read()
                data = bytes_to_yaml(content)
            elif resource == "secret":
                content = self.core_api.read_namespaced_secret(namespace=namespace, name=name, _preload_content=False).read()
                data = bytes_to_yaml(content)
            elif resource == "clusterrole":
                content = self.rbac_api.read_cluster_role(name=name, _preload_content=False).read()
                data = bytes_to_yaml(content)
            elif resource == "clusterrolebinding":
                content = self.rbac_api.read_cluster_role_binding(name=name, _preload_content=False).read()
                data = bytes_to_yaml(content)
            elif resource == "role":
                content = self.rbac_api.read_namespaced_role(namespace=namespace, name=name, _preload_content=False).read()
                data = bytes_to_yaml(content)
            elif resource == "rolebinding":
                content = self.rbac_api.read_namespaced_role_binding(namespace=namespace, name=name, _preload_content=False).read()
                data = bytes_to_yaml(content)
            code = 200
            msg = "成功"
        except Exception as e:
            code = 500
            msg = "获取YAML失败：%s" %e

        res = {'code': code, 'msg': msg, 'data': data}
        return JsonResponse(res)


class apply_yaml(View):

    k8s.load_auth_config()
    core_api = client.CoreV1Api()  # namespace,pod,service,pv,pvc
    apps_api = client.AppsV1Api()  # deployment
    networking_api = client.NetworkingV1Api()  # ingress
    storage_api = client.StorageV1Api()  # storage_class
    rbac_api = client.RbacAuthorizationV1Api()  # rbac

    def post(self,request):

        try:
            data = json.loads(request.body.decode("utf-8"))
            yaml_content = data['yaml_content']
            content = yaml.safe_load(yaml_content) # yaml转字典
            resource = content['kind']

            if not resource == "Node":
                namespace = content['metadata']['namespace']
            else:
                namespace = None
            name = content['metadata']['name']

            if resource == "Node":
                result = {'code': 500, 'msg': 'Node资源不支持更新！'}
                return JsonResponse(result)
            elif resource == "Namespace":
                self.core_api.patch_namespace(body=content, name=name)
            elif resource == "Deployment":
                self.apps_api.patch_namespaced_deployment(body=content, namespace=namespace, name=name)
            elif resource == "DaemonSet":
                self.apps_api.patch_namespaced_daemon_set(body=content, namespace=namespace, name=name)
            elif resource == "StatefulSet":
                self.apps_api.patch_namespaced_stateful_set(body=content, namespace=namespace, name=name)
            elif resource == "Pod":
                self.core_api.patch_namespaced_pod(body=content, namespace=namespace, name=name)
            elif resource == "Service":
                self.core_api.patch_namespaced_service(body=content, namespace=namespace, name=name)
            elif resource == "Ingress":
                self.networking_api.patch_namespaced_ingress(body=content, namespace=namespace, name=name)
            elif resource == "PersistentVolume":
                self.core_api.patch_persistent_volume(body=content, name=name)
            elif resource == "PersistentVolumeClaim":
                self.core_api.patch_namespaced_persistent_volume_claim(body=content, namespace=namespace, name=name)
            elif resource == "StorageClass":
                self.storage_api.patch_storage_class(body=content, name=name)
            elif resource == "ConfigMap":
                self.core_api.patch_namespaced_config_map(body=content, namespace=namespace, name=name)
            elif resource == "Secret":
                self.core_api.patch_namespaced_secret(body=content, namespace=namespace, name=name)
            elif resource == "ClusterRole":
                self.rbac_api.patch_cluster_role(body=content, name=name)
            elif resource == "ClusterRoleBinding":
                self.rbac_api.patch_cluster_role_binding(body=content, name=name)
            elif resource == "Role":
                self.rbac_api.patch_namespaced_role(body=content, namespace=namespace, name=name)
            elif resource == "RoleBinding":
                self.rbac_api.patch_namespaced_role_binding(body=content, namespace=namespace, name=name)
            code = 200
            msg = "更新成功"
        except Exception as e:
            code = 500
            msg = "更新失败：%s" % e

        res = {'code': code, 'msg': msg}
        return JsonResponse(res)


class ace_editor_apply_yaml(View):

    k8s.load_auth_config()
    k8s_client = client.ApiClient()

    def post(self,request):
        try:
            data = json.loads(request.body.decode("utf-8"))
            yaml_content = data['yaml_content']
            content = yaml.safe_load(yaml_content)  # yaml转字典
            utils.create_from_dict(self.k8s_client, content)
            code = 200
            msg = '应用成功'
        except Exception as e:
            msg = "应用失败！%s" %e
            code = 500
        res = {'code': code, 'msg': msg}
        return JsonResponse(res)


class node_resource(View):

    k8s.load_auth_config()
    core_api = client.CoreV1Api()

    def get(self,request):
        try:
            data = node_data.node_resource(self.core_api)
            code = 200
            msg = '获取成功'
            res = {'code': code, 'msg': msg, 'data': data}
        except Exception as e:
            code = 500
            msg = f'获取失败:{e}'
            res = {'code': code, 'msg': msg}

        return JsonResponse(res)